import React, {useState, useEffect} from 'react';
import { Select, message, Spin } from 'antd';
import { TableListItem } from '../../Plan/data.d';
import { planList } from '../../Plan/service';

interface OrgTypeProps {
  orgId:number;
  value:string;
  disabled:boolean;
  selectChange: (values:any) => void;
}

const { Option } = Select;
/**
 * 
 * 所属机构控件
 */
const PlanListComponent: React.FC<OrgTypeProps> = (props) => {

  const { orgId,disabled,value,selectChange } = props;

  const [data, setData] = useState<[]>([]);
  const [scrollPage , setScrollPage ] = useState<number>(1);
  const [load, setLoad] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);

  const getData = (page:number) =>{
    // console.log("页数: "+page);
    const params = new Object();
    params["pageSize"]= 10;
    params["pageNo"]= page;
    params["current"]= page;
    params["orgId"] = orgId;
    setLoading(true);
    new Promise((resolve, reject) => {
      planList(params)
        .then((res) => {
          if (res) {
            // console.log(data);
            // console.log(res.data);
            const data1 = res.data;
            if(data1 && data1.length > 0){
              if(page == 1){
                setData(data1);
              }else{
                setData([...data,...data1]);
              }
              
            }else{
              setLoad(false);
            }
            resolve(true);
          } else {
            message.error('请求失败');
            resolve(false);
          }
          setLoading(false);
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  }

  const companyScroll = (e) => { //下拉列表滚动时的回调
    e.persist();
    const { target } = e;
    if (target.scrollTop + target.offsetHeight === target.scrollHeight && load) {
      const nextScrollPage = scrollPage + 1;
      setScrollPage(nextScrollPage);
      getData(nextScrollPage);
     }
  }

  return (
      <Select
        allowClear
        placeholder="请选择当前计划"
        optionFilterProp="children"
        disabled={disabled}
        value={value}
        style={{ width: 200 }}
        onChange={(values) =>selectChange(values)}
        onFocus={() => {
          setLoad(true);
          setData([]);
          setScrollPage(1);
          getData(1);
        }}
        onPopupScroll={companyScroll}
        dropdownRender={menu => (
          <div>
            {menu}
            <div
              className="selectScroll"
              style={{ textAlign: 'center' }}
              onMouseDown={e => e.preventDefault()}
            >
              {
                loading && // 加载状态
                  <Spin size="small" style={{ padding: '8px' }} />
              }
            </div>
          </div>
        )}
      >
        {data?.map((item:TableListItem) => <Option key={item.id} value={item.id}>{item.name}</Option>)}
    </Select>
  );
};

export default PlanListComponent;
